<template>
  <div>
    <!-- 面包屑区域    -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <el-alert
        title="注意：只允许为第三季分类设置相关参数!"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>

      <!-- 选择商品分类级联框 -->
      <el-row class="alert">
        <el-col>
          选择商品分类：
          <el-cascader
            v-model="selectKeys"
            :options="options"
            :props="cascaderProps"
            @change="changeCategories"
            filterable
            clearable
            ref="cascaderRef"
          ></el-cascader>
        </el-col>
      </el-row>

      <!-- tabs切换 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 动态参数面板 -->
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加参数按钮 -->
          <el-row>
            <el-col>
              <el-button
                type="primary"
                :disabled="!selectKeys.length"
                @click="addParams"
                >添加参数</el-button
              >
            </el-col>
          </el-row>

          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scoped">
                <!-- 渲染tag标签 -->
                <el-tag
                  v-for="(item, index) in scoped.row.attr_vals"
                  :key="index"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(scoped.row, index)"
                >
                  {{ item }}
                </el-tag>
                <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scoped.row.inputVisible"
                  v-model="scoped.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scoped.row)"
                  @blur="handleInputConfirm(scoped.row)"
                >
                </el-input>
                <!-- 添加按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scoped.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column
              type="index"
              label="编号"
              width="49px"
            ></el-table-column>
            <el-table-column label="参数名称" prop="attr_name">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scoped">
                <!-- 修改按钮 -->
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editParam(scoped.row)"
                  >编辑</el-button
                >
                <!-- 删除按钮 -->
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteCate(scoped.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 静态属性面板 -->
        <el-tab-pane label="静态属性" name="only">
          <!-- 添加属性按钮 -->
          <el-row>
            <el-col>
              <el-button
                type="primary"
                :disabled="!selectKeys.length"
                @click="addStaticParams"
                >添加属性</el-button
              >
            </el-col>
          </el-row>

          <!-- 静态属性表格 -->
          <el-table :data="onlyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scoped">
                <!-- 渲染tag标签 -->
                <el-tag
                  v-for="(item, index) in scoped.row.attr_vals"
                  :key="index"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(scoped.row, index)"
                >
                  {{ item }}
                </el-tag>
                <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scoped.row.inputVisible"
                  v-model="scoped.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scoped.row)"
                  @blur="handleInputConfirm(scoped.row)"
                >
                </el-input>
                <!-- 添加按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scoped.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column
              type="index"
              label="编号"
              width="49px"
            ></el-table-column>
            <el-table-column label="属性名称" prop="attr_name">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scoped">
                <!-- 修改按钮 -->
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editParam(scoped.row)"
                  >编辑</el-button
                >
                <!-- 删除按钮 -->
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteCate(scoped.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数对话框 -->
    <el-dialog
      :visible.sync="addParamsDialog"
      :title="title"
      width="50%"
      @close="closeAddParamsDialog"
    >
      <el-form
        :model="addParamsForm"
        :rules="addParamsFormRules"
        ref="addParamsFormRef"
        label-width="100px"
        status-icon
      >
        <el-form-item :label="labelText" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsDialog = false">取 消</el-button>
        <el-button type="primary" @click="submitAddParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //级联选择器的下来选项的数据
      options: [],
      //级联选择器数据的定义
      cascaderProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      //选中的分类的id数组
      selectKeys: [],
      activeName: 'many',
      //存储选定动态参数的数据
      manyTableData: [],
      //存储选定静态态参数的数据
      onlyTableData: [],
      //存储选中分类的id
      cateId: '',
      //控制添加参数对话框的显示与隐藏
      addParamsDialog: false,
      //添加或修改参数表单
      addParamsForm: {
        attr_name: '',
        attr_sel: 'many'
      },
      //添加或修改参数的校验规则
      addParamsFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
          {
            min: 2,
            max: 20,
            message: '参数名称长度为2~20个字符',
            trigger: 'blur'
          }
        ]
      },
      //弹框的标题
      title: '添加动态参数',
      //存储要修改的参数的id
      editParamId: ''
    }
  },
  created() {
    //获取所有的分类
    this.getAllCategories()
  },
  methods: {
    //获取所有的分类
    async getAllCategories() {
      const res = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      //获取成功，吧返回的数据赋给options
      this.options = res.data
    },
    changeCategories() {
      console.log(this.selectKeys)
      //获取选中分类的三级分类的id,就是selectKeys的最后一个值
      //获取对应的分类id并存储起来以便删除参数操作
      this.cateId = this.selectKeys[this.selectKeys.length - 1]
      //获取对应动态参数
      this.getParamsData()
    },
    //获取动态或静态参数
    async getParamsData() {
      //只允许为第三级分类设置相关参数!所以选择一级和二级的时候将选择器清空
      if (this.selectKeys.length <= 2) {
        //清空选中的id数组
        this.selectKeys = []
        //清空参数数据
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      const res = await this.$http.get(
        `categories/${this.cateId}/attributes?sel=` + this.activeName
      )
      //对获取到的数据做一下处理
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        //控制文本框的显示与隐藏
        item.inputVisible = false
        //存储文本框输入的值
        item.inputValue = ''
      })
      if (res.meta.status !== 200)
        return this.$message.info('请先选择对应的分类')
      //方便易读这里把得到的数据做一个判断分别赋给不同的数组接收
      if (this.activeName === 'many') {
        //动态数据
        this.manyTableData = res.data
      } else {
        //静态数据
        this.onlyTableData = res.data
      }
    },
    //监听tab页签点击事件
    handleClick() {
      console.log(this.activeName)
      this.getParamsData()
    },
    //删除动态参数和静态参数
    deleteCate(cateId) {
      //根据当前id删除对应的参数
      this.$MessageBox
        .confirm('此操作将永久删除该参数，是否继续?', '删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(async () => {
          const res = await this.$http.delete(
            `categories/${this.cateId}/attributes/${cateId}`
          )
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
          //删除成功
          this.$message.success(res.meta.msg)
          //重新获取参数
          this.getParamsData()
        })
        .catch(() => this.$message.info('删除操作已取消'))
    },
    //点击添加按钮显示添加弹框
    addParams() {
      this.addParamsDialog = true
    },
    //点击确定进行参数添加
    submitAddParams() {
      //对title进行判断
      if (this.title === '修改动态参数' || this.title === '修改静态属性') {
        //证明是修改操作
        this.$refs.addParamsFormRef.validate(async valid => {
          if (!valid) {
            //校验失败
            return
          }
          //根据Id修改参数
          const res = await this.$http.put(
            `categories/${this.cateId}/attributes/${this.editParamId}`,
            this.addParamsForm
          )
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
          //修改成功
          this.$message.success(res.meta.msg)
          // 隐藏弹框
          this.addParamsDialog = false
          //重置表单
          this.closeAddParamsDialog()
          //重新获取参数列表
          this.getParamsData()
        })
      } else {
        //添加操作
        //预校验表单
        this.$refs.addParamsFormRef.validate(async valid => {
          if (!valid) {
            //校验失败，阻止程序向下执行
            return
          }
          //校验成功
          const res = await this.$http.post(
            `categories/${this.cateId}/attributes`,
            this.addParamsForm
          )
          if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
          //创建成功
          this.$message.success(res.meta.msg)
          //关闭弹框
          this.addParamsDialog = false
          //重置表单
          this.closeAddParamsDialog()
          //重新获取参数列表
          this.getParamsData()
        })
      }
    },
    //监听表单的关闭事件
    closeAddParamsDialog() {
      this.$refs.addParamsFormRef.resetFields()
      this.addParamsForm.attr_name = ''
      this.addParamsForm.attr_sel = 'many'
      this.title = '添加动态参数'
    },
    //点击添加静态属性的按钮弹出输入框
    addStaticParams() {
      //把弹框的名称修改为添加静态参数
      this.title = '添加静态属性'
      //显示弹框
      this.addParamsDialog = true
      //把参数表单的attr_sel改为only
      this.addParamsForm.attr_sel = this.activeName
    },
    //修改动态参数或者静态属性,点击编辑按钮显示弹框，并根据id查询对应的参数和属性
    async editParam(param) {
      //1.显示弹框
      this.addParamsDialog = true
      //2.存储要修改参数的id以便修改操作
      this.editParamId = param.attr_id
      //3.把标题修改为修改动态参数或者静态属性
      this.title = this.activeName == 'many' ? '修改动态参数' : '修改静态属性'
      //4.根据id查询对应的参数
      const res = await this.$http.get(
        `categories/${this.cateId}/attributes/${param.attr_id}`,
        { params: { attr_sel: this.activeName } }
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      //3.获取成功，把返回的数据赋值给addParamsForm.attr_name
      this.addParamsForm.attr_name = res.data.attr_name
      //4.把sel修改为many或者only
      this.addParamsForm.attr_sel = this.activeName
    },
    //监听tag标签的关闭事件
    handleClose(row, index) {
      this.$MessageBox
        .confirm('次操作将永久删除该用户,是否继续', '删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          //根据传递过来的索引删除对应的tag
          row.attr_vals.splice(index, 1)
          //以空格分割为一个字符串
          let str = row.attr_vals.join(' ')
          //调用修改对应的参数和属性的函数
          this.addParamsCate(row.attr_id, {
            attr_name: row.attr_name,
            attr_sel: row.attr_sel,
            attr_vals: str
          })
          //隐藏输入框显示按钮
          row.inputVisible = false
          //把输入的值清空
          row.inputValue = ''
        })
        .catch(() => this.$message.info('取消删除操作'))
    },
    //修改对应的参数和属性
    async addParamsCate(aId, options, flag) {
      const res = await this.$http.put(
        `categories/${this.cateId}/attributes/${aId}`,
        options
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      //获取成功
      this.$message.success(flag ? '添加成功' : '删除成功')
    },
    //文本框失去焦点或者按下回车键触发
    handleInputConfirm(row) {
      //判断用户是否输入了内容
      if (row.inputValue.length === 0) {
        this.$message.error('请输入内容')
        //把输入的值清空
        row.inputValue = ''
        //隐藏输入框显示按钮
        row.inputVisible = false
        //阻止程序向下执行
        return
      }
      //如果没有return，证明输入了内容，需要做后续处理
      //把输入的内容追加到数组中
      row.attr_vals.push(row.inputValue)
      //以空格分割为一个字符串
      let str = row.attr_vals.join(' ')

      //调用修改对应的参数和属性的函数
      this.addParamsCate(
        row.attr_id,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: str
        },
        row.inputVisible
      )
      //隐藏输入框显示按钮
      row.inputVisible = false
      //把输入的值清空
      row.inputValue = ''
    },
    // 点击按钮显示文本输入框
    showInput(row) {
      //显示输入框
      row.inputVisible = true
      //$nextTick()方法的作用
      //就是当页面上的元素被重写渲染之后，才会执行回调函数中的代码
      this.$nextTick(_ => {
        //让文本框处于输入状态
        this.$refs.saveTagInput.$refs.input.focus()
      })
    }
  },
  computed: {
    labelText() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}
</script>

<style lang="less" scoped>
.alert {
  margin: 18px 0;
}
.el-tag {
  margin-left: 18px;
}
.button-new-tag {
  margin-left: 18px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 120px;
  margin-left: 18px;
  vertical-align: bottom;
}
</style>
